# coding: utf-8

from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_user, logout_user, login_required, current_user
from flask_principal import Permission, RoleNeed
from flask_login import LoginManager
from user.forms import UserAddForm, UserEditForm
from db.models import db, User, BorrowBook
from permission_control import permission_required
from const import PERMISSION, BorrowCardApplyStatus
from log import logger
from config import app

borrow_manage_blueprint = Blueprint('borrow_manage', __name__)


@borrow_manage_blueprint.route('/borrow_manage/list', methods=['GET'])
@login_required
@permission_required(PERMISSION.PERM_BOOK_HANDLE_BORROW.KEY)
def borrow_list():
    logger.info(request.args)
    if "all" in request.args:
        borrow_books = BorrowBook.query.all()
    else:
        filter_condition = request.args
        borrow_books = BorrowBook.query.filter_by(**filter_condition).order_by(BorrowBook.id.desc()).all()
    return render_template('borrow_manage/borrows.html', borrow_books=borrow_books)


@borrow_manage_blueprint.route('/user_manage/is_active/<int:user_id>/<int:is_active>', methods=['GET', 'POST'])
@login_required
@permission_required(PERMISSION.PERM_BOOK_HANDLE_BORROW.KEY)
def user_active(user_id, is_active):
    if is_active not in [0, 1]:
        flash('无效的操作。', 'danger')
        return redirect(url_for('borrow_manage.borrow_list'))
    user = User.query.filter_by(id=user_id).first()
    user.is_active = is_active
    db.session.commit()
    if is_active == 1:
        flash('用户信息已激活！', 'success')
    else:
        flash('用户信息已禁用！', 'success')
    return redirect(url_for('borrow_manage.borrow_list'))
